package com.mathew.spring.appsp.controller.AsyncController;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

@RestController
public class DomController {

  @GetMapping("/dom/getDefer")
  public DeferredResult<String> getDefer() {
    String uuid = UUID.randomUUID().toString();
    DeferredResult<String> deferredResult = new DeferredResult<>((long) 60 * 1000);
    deferredResult.setResult(uuid);
    deferredResult.onCompletion(() -> {
    });
    return deferredResult;
  }

  @GetMapping("/dom/getAsync")
  public Callable<String> getAsync() {
    Callable<String> callable = () -> String.valueOf(System.currentTimeMillis());
    return callable;
  }

  @GetMapping("/dom/bodyEmitter")
  public ResponseBodyEmitter getBodyEmitter() {

    ResponseBodyEmitter responseBodyEmitter = new ResponseBodyEmitter();
    Executors.newSingleThreadExecutor().submit(()->{
      try {
        responseBodyEmitter.send("dom");
        responseBodyEmitter.send("bodyEmitter");
      } catch (IOException e) {
        e.printStackTrace();
      }
      responseBodyEmitter.complete();
    });
    return responseBodyEmitter;
  }
}
